package controller.admins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import dao.admins.IGoodsQuery;
import dao.admins.impl.GoodsQueryImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import pojo.Goods;
import util.pagingOpt.impl.GoodsImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@WebServlet(name = "DoGoodsServlet", urlPatterns = "/doGoods")
public class DoGoodsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        GoodsQueryImpl goodsQuery = new GoodsQueryImpl();
        String action = request.getParameter("action");
        if ("goodsQuery".equals(action)) {
            goodsQuery(request);
            request.getRequestDispatcher("/page/goods/goodsQuery.jsp").forward(request, response);
        } else if ("goodsQueryById".equals(action)) {
            goodsQueryById(request, goodsQuery);
            request.getRequestDispatcher("/page/goods/goodsUpdate.jsp").forward(request, response);
        } else if ("goodsUpdate".equals(action)) {
            goodsUpdate(request, goodsQuery);
            goodsQuery(request);
            request.getRequestDispatcher("/page/goods/goodsQuery.jsp").forward(request, response);
        } else if ("goodsAdd".equals(action)) {
//            System.out.println("执行了");
            goodsAdd(request, goodsQuery);
            goodsQuery(request);
            request.getRequestDispatcher("/page/goods/goodsQuery.jsp").forward(request, response);
        } else if ("goodsDelById".equals(action)) {
            goodsDelById(request, goodsQuery);
            goodsQuery(request);
            request.getRequestDispatcher("/page/goods/goodsQuery.jsp").forward(request, response);
        } else if ("paging".equals(action) || "goodsQueryLike".equals(action)) {
            PrintWriter out = response.getWriter();
            int pageNo = Integer.parseInt(request.getParameter("pageNo"));
            String pageSupportJson = JSON.toJSONString(paging(pageNo, request).getPageEntity());
//            System.out.println(paging(pageNo, request).getPageEntity().getLists());
            out.write(pageSupportJson);
        } else if ("optionS".equals(action)){
            PrintWriter out = response.getWriter();
//            int pageNumber = Integer.parseInt(request.getParameter("pageNo"));
            JSONObject json = new JSONObject();
//            json.put("sellerName", goodsQuery.optionS());
//            json.put("smallName", goodsQuery.optionC());
//            System.out.println(goodsQuery.optionS());
//            System.out.println(goodsQuery.optionC());
//            System.out.println(json);
//            out.print(json);
//            System.out.println("这里执行过了！");
            Map<Integer, String > sellers = goodsQuery.optionS();
            for(Integer i : sellers.keySet()){
                json.put("" + i, sellers.get(i));
            }
            out.print(json);

        }else if ("optionC".equals(action)){
            PrintWriter out = response.getWriter();
            JSONObject json = new JSONObject();
            Map<Integer, String > smalls = goodsQuery.optionC();
            for(Integer i : smalls.keySet()){
                json.put("" + i, smalls.get(i));
            }
            out.print(json);
//            System.out.println(json);
        }else if ("optionD".equals(action)){
            PrintWriter out = response.getWriter();
            JSONObject json = new JSONObject();
            Map<Integer, Double > smalls = goodsQuery.optionD();
            for(Integer i : smalls.keySet()){
                json.put("" + i, smalls.get(i));
            }
            out.print(json);
//            System.out.println(json);
        }
    }

    private void goodsQuery(HttpServletRequest request) {
        List<Goods> goods = paging(1, request).getList();
        request.setAttribute("pageData", goods);
        request.setAttribute("pageNumber", request.getParameter("pageNumber"));
    }

    private void goodsQueryById(HttpServletRequest request, GoodsQueryImpl goodsQuery) {
        long id = Long.valueOf(request.getParameter("id"));
//        System.out.println(goodsQuery.queryGoodsById(id));
        request.setAttribute("All", goodsQuery.queryGoodsById(id));
        request.setAttribute("goodsSmalId", goodsQuery.optionC());
        request.setAttribute("goodsSeId", goodsQuery.optionS());
        request.setAttribute("goodsDiscId", goodsQuery.optionD());
    }

    private void goodsUpdate(HttpServletRequest request, IGoodsQuery goodsQuery) {
        Goods goods = new Goods();
//        System.out.println("id " + request.getParameter("id"));
//        System.out.println("goodsName " + request.getParameter("goodsName"));
//        System.out.println("goodsSmalId " + request.getParameter("goodsSmalId"));
//        System.out.println("goodsMoney " + request.getParameter("goodsMoney"));
//        System.out.println("goodsNumber " + request.getParameter("goodsNumber"));
//        System.out.println("goodsImage " + request.getParameter("goodsImage"));
//        System.out.println("goodsCarriage " + request.getParameter("goodsCarriage"));
//        System.out.println("goodsType " + request.getParameter("goodsType"));
//        System.out.println("goodsSeId " + request.getParameter("goodsSeId"));
//        System.out.println("goodsDiscId " + request.getParameter("goodsDiscId"));
        GoodsQueryImpl.setGoods(goods, Long.valueOf(request.getParameter("id")), request.getParameter("goodsName"), Long.valueOf(request.getParameter("goodsSmalId")),
                Double.parseDouble(request.getParameter("goodsMoney")), Integer.parseInt(request.getParameter("goodsNumber")), request.getParameter("goodsImage"), Double.parseDouble(request.getParameter("goodsCarriage")),
                Integer.parseInt(request.getParameter("goodsType")), Integer.parseInt(request.getParameter("goodsSeId")), Integer.parseInt(request.getParameter("goodsDiscId")));
        goodsQuery.updateGoods(goods);
    }

    private void goodsAdd(HttpServletRequest request, IGoodsQuery goodsQuery) {
        Goods goods = new Goods();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    String itemName = item.getFieldName();
                    if (item.isFormField()) {
                        if (itemName.equals("goodsName")) {
                            goods.setGoodsName(item.getString("utf-8"));
                        } else if (itemName.equals("goodsSmalId")) {
                            goods.setGoodsSmalId(Integer.parseInt(item.getString("utf-8")));
                        } else if (itemName.equals("goodsMoney")) {
                            goods.setGoodsMoney(Double.parseDouble(item.getString("utf-8")));
                        } else if (itemName.equals("goodsNumber")) {
                            goods.setGoodsNumber(Integer.parseInt(item.getString("utf-8")));
                        } else if (itemName.equals("goodsCarriage")) {
                            goods.setGoodsCarriage(Double.parseDouble(item.getString("utf-8")));
                        } else if (itemName.equals("goodsType")) {
                            goods.setGoodsType(Integer.parseInt(item.getString("utf-8")));
                        } else if (itemName.equals("goodsSmalId")) {
                            goods.setGoodsSmalId(Integer.parseInt(item.getString("utf-8")));
                        } else if (itemName.equals("goodsSeId")) {
                            goods.setGoodsSeId(Integer.parseInt(item.getString("utf-8")));
                        } else if (itemName.equals("goodsDiscId")) {
                            goods.setGoodsDiscId(Integer.parseInt(item.getString("utf-8")));
                        }
                    } else {
                        String path = request.getSession().getServletContext().getRealPath("GoodsImage");
//                        System.out.println(path);
                        String fileName = item.getName();
//                        System.out.println(fileName);
                        if (fileName != null && !fileName.equals("")) {
                            File fullFile = new File(fileName);
                            File saveFile = new File(path, fullFile.getName());//将文件保存到指定的路径
                            item.write(saveFile);
                            goods.setGoodsImage(fileName);
//                            File file = new File(path, fileName);
//                            item.write(file);
//                            goods.setGoodsImage(fileName);
                        }
                    }
                }
                goodsQuery.addGoods(goods);
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void goodsDelById(HttpServletRequest request, IGoodsQuery goodsQuery) {
        long id = Integer.parseInt(request.getParameter("id"));
        goodsQuery.deleteGoods(id);
    }

    private GoodsImpl paging(int pageNo, HttpServletRequest request) {
        String goodsName = request.getParameter("goodsName");
//        System.out.println(goodsName);
        String sellerName = request.getParameter("sellerName");
        String smallNameId = request.getParameter("smallName");
//        System.out.println(goodsName);
//        System.out.println(sellerName);
//        System.out.println(smallNameId);
        StringBuffer sqlQuery = new StringBuffer("select count(*) from goods where 1 = 1");
        StringBuffer sqlPaging = new StringBuffer("SELECT goods.`id`, goods.goodsName, `smallclass`.smallName," +
                " goodsMoney, goodsNumber, goodsImage, goodsCarriage, goodsType, seller.`sellerName`, discount.`discRate`" +
                "FROM goods INNER JOIN seller ON goods.`goodsSeId` = seller.`id` " +
                "INNER JOIN `smallclass` ON goods.`goodsSmalId` = smallclass.`id` " +
                "INNER JOIN discount ON goods.`goodsDiscId` = discount.`id` where 1 = 1 ");
        if (goodsName != null && goodsName != ""){
            sqlQuery.append(" and goodsName like '%" + goodsName + "%' ");
            sqlPaging.append(" and goodsName like '%" + goodsName + "%' ");
        }
        if (sellerName != null && Integer.parseInt(sellerName) > 0){
            sqlQuery.append(" and goodsSeId = " + Integer.parseInt(sellerName) + " ");
            sqlPaging.append(" and goodsSeId = " + Integer.parseInt(sellerName) + " ");
        }
        if (smallNameId != null && Integer.parseInt(smallNameId) > 0){
            sqlQuery.append(" and goodsSmalId = " + Integer.parseInt(smallNameId) + "");
            sqlPaging.append(" and goodsSmalId = " + Integer.parseInt(smallNameId) + " ");
        }
        sqlPaging.append(" limit ?, ?");
//        System.out.println(sqlQuery);
//        System.out.println(sqlPaging);
        GoodsImpl goodsImpl = new GoodsImpl(3, sqlQuery.toString(), sqlPaging.toString());
        goodsImpl.setCurrentPage(pageNo);
        return goodsImpl;
    }
}
